package com.hudilao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hudilao.common.R;
import com.hudilao.dto.CartAddDTO;
import com.hudilao.dto.CartItemDTO;
import com.hudilao.entity.Cart;
import com.hudilao.entity.Dish;
import com.hudilao.entity.Setmeal;
import com.hudilao.mapper.CartMapper;
import com.hudilao.service.CartService;
import com.hudilao.service.DishService;
import com.hudilao.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public List<Cart> add(CartAddDTO cartAddDTO, long customerId) {


        List<Cart> updatedCartItems = new ArrayList<>();
        for(CartItemDTO cartItemDTO : cartAddDTO.getCartItemDTOS()){
            Long id = cartItemDTO.getId();
            Integer quantity = cartItemDTO.getQuantity();

            LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Cart::getCustomerId,customerId);
            queryWrapper.eq(Cart::getItemId,cartItemDTO.getId());


            //查询当前菜品或套餐是否在购物车中
            Cart cartServiceOne = this.getOne(queryWrapper);

            if(cartServiceOne != null){
                Integer number = cartServiceOne.getNumber();
                cartServiceOne.setNumber(number+1);
                this.updateById(cartServiceOne);
            }else{
                //加入购物车
                Cart cart = new Cart();
                cart.setCustomerId(customerId);
                cart.setItemId(id);
//                cart.setDishId(dishId);
//                cart.setSetMealId(setmealId);

                cart.setNumber(quantity);
                cart.setType(cartItemDTO.getType());

                if (cartItemDTO.getType() == 1) {
                    // 如果是菜品，设置菜品名称和价格
                    Dish dish = dishService.getById(id);
                    cart.setName(dish.getName());
                    cart.setAmount(dish.getPrice());
                } else {
                    // 如果是套餐，设置套餐名称和价格
                    Setmeal setmeal = setmealService.getById(id);
                    cart.setName(setmeal.getName());
                    cart.setAmount(setmeal.getPrice());
                }

                this.save(cart);
                updatedCartItems.add(cart);
            }
        }

        return updatedCartItems;
    }

    @Override
    public void remove(long customerId) {

        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getCustomerId,customerId);
        this.remove(queryWrapper);
    }
}
